/**
 * Created by liubin on 2015/09/02.
 */
'use strict';

import Joi from 'joi';
import _ from 'lodash';

const joiOptions = {
    abortEarly: false,
    allowUnknown: true
};
function format(joiResult) {
    if (joiResult.error !== null) {
        return joiResult.error.details.reduce((memo, detail) => {
            //if (!Array.isArray(memo[detail.path])) {
            //    memo[detail.path] = [];
            //}
            //memo[detail.path].push(detail.message);
            //return memo;
            if (!memo[detail.path]) {
                memo[detail.path] = detail.message;
            }
            return memo;
        }, {});
    } else {
        return {};
    }
}
export default function joiValidatorAsync(joiSchema) {
    return (data, dispatch) => {
        const errors = format(Joi.validate(data, joiSchema, joiOptions));
        _.union(Object.keys(joiSchema), Object.keys(data)).forEach(error => {
            errors[error] = errors[error] || '';
        });
        return new Promise((resolve, reject) => {
            resolve(errors);
        });
    };
}